//库存管理(库存->库存管理)--------------------------------------------------------------------
function warehouseAdmin() {
    //导航菜单库存管理鼠标单击事件
    $(document).on("click", ".warehouse-admin", function() {
        //找到激活的导航项，并移除激活css
        $("#my-navbar-1-nav").find('li.my-navbar-1-nav-li-active').removeClass("my-navbar-1-nav-li-active");
        //为库存添加激活css
        $(".warehouse-admin").parent().parent().addClass('my-navbar-1-nav-li-active');
        //清空#main-body
        $("#main-body").empty();
        //加载warehouse-admin.html，并执行函数
        $("#main-body").load("static/html/warehouse-admin.html", function() {
            //清空小导航
            $("#navbar-2").empty();
            //填充小导航
            var node = $(".warehouse-admin");
            var fNode = node.parent();
            var cnode = node.clone();
            var cnav = fNode.clone().removeClass('dropdown-menu').addClass('nav navbar-nav');
            cnav.find('.warehouse-admin').addClass("active");
            $("#navbar-2").append(cnav);

            //左侧边warehouse tree显示
            warehouseTree("sideTree", "aside.tree");
            var stree = $.fn.zTree.getZTreeObj("sideTree");
            //设置鼠标点击事件
            stree.setting.callback.onClick = function(event, treeId, treeNode, clickFlag) {
                //如果当前节点没有父节点
                if (treeNode.isParent == false) {
                    //加载产品列表页
                    goodsAdmin(treeNode);
                } else {
                    //父节点管理界面
                    $("#content").empty();
                }
            };
        });

    });

}

//单击warehouse tree中的节点，加载产品列表页
function goodsAdmin(wTreeNode) {
    //如果dom中没有#my-table，添加
    if ($("#my-table").length < 1) {
        $("<div id=\"my-table\" class=\"my-table\"></div>").appendTo($("#content"));
    }
    //如果dom中没有#my-table-nav，添加
    if ($("#my-table-nav").length < 1) {
        $("<div id=\"my-table-nav\" class=\"my-table-nav\"></div>").appendTo($("#content"));
    }
    //清空表格
    $("#my-table").empty();
    //清空表格分页
    $("#my-table-nav").empty();
    //物品列表(BUI表格插件)
    BUI.use(['bui/grid', 'bui/data', 'bui/toolbar'], function(Grid, Data, Toolbar) {
        //总记录数
        var totalCount = 0;
        //获取总页数
        var totalPage = 0;
        //每页记录数
        var pageSize = 3;
        //开始数
        var offset = 0;

        var data = postData(BUI.JSON.stringify({
            Warehouseid: wTreeNode.Id
        }), "/green/goods/count");
        if (data.ServerError == false) { //数据库操作OK
            if (data.Data > 0) {
                totalCount = data.Data;
                totalPage = totalCount / pageSize;
                totalPage = Math.ceil(totalPage);
            }
        }

        var Grid = Grid,
            Store = Data.Store,
            columns = [{
                title: '物品编号',
                dataIndex: '_number',
                sortable: false,
                width: '14%'
            }, {
                title: '名称',
                dataIndex: '_name',
                sortable: false,
                width: '14%'
            }, {
                title: '规格',
                dataIndex: '_specification',
                sortable: false,
                width: '16%'
            }, {
                title: '数量',
                dataIndex: '_quantity',
                sortable: false,
                width: '14%'
            }, {
                title: '数量单位',
                dataIndex: '_quantityunit',
                sortable: false,
                width: '14%'
            }, {
                title: '参考价格',
                dataIndex: '_price',
                sortable: false,
                width: '14%'
            }, {
                title: '价格单位',
                dataIndex: '_priceunit',
                sortable: false,
                width: '14%'
            }];

        var store = new Store({
            autoLoad: true,
            pageSize: pageSize, // 需要在store中 配置pageSize
            proxy: {
                url: "/green/goods/list/" + wTreeNode.Id + "/" + pageSize + "/" + offset,
                method: 'get',
                dataType: 'json',
                pageStart: 1
            }
        });

        var grid = new Grid.Grid({
            render: '#my-table',
            columns: columns,
            width: "100%",
            store: store,
            loadMask: true,
            emptyDataTpl: "<div class=\"centered\"><h2>查询的数据不存在</h2></div>",
            multipleSelect: true,
            plugins: [Grid.Plugins.CheckSelection],
            tbar: {
                elCls: "row",
                items: [{
                    btnCls: 'btn btn-primary btn-sm goods-create-btn',
                    text: '新增',
                    listeners: {
                        'click': function() {
                            BUI.use(['bui/overlay', 'bui/form'], function(Overlay, Form) {
                                var bui_form;
                                var dialog = new Overlay.Dialog({
                                    title: '新建物品',
                                    width: 500,
                                    height: 480,
                                    //关闭后删除dialog
                                    closeAction: 'destroy',
                                    //控件加载内容DIV
                                    bodyContent: "<div id=\"create-content\"></div>",
                                    success: function() {
                                        if (bui_form.isValid()) { //form验证OK
                                            var obj = bui_form.serializeToObject();
                                            obj.Warehouseid = wTreeNode.Id;
                                            obj.Quantity = parseFloat(obj.Quantity);
                                            obj.Price = parseFloat(obj.Price);
                                            var data = postData(BUI.JSON.stringify(obj), "/green/goods/create");
                                            if (data.Status == 0) { //数据库操作OK
                                                this.close();
                                                store.load();
                                                store.on("load", function() {
                                                    grid.setSelectedByField('_id', data.Data);
                                                });
                                            } else if (data.Status == -1) {
                                                $("#create-and-edit-one-goods-form").find('div.create-goods-dialog-err').empty().css({
                                                    "color": "red",
                                                    "text-align": "center"
                                                }).text("请修改编号，数据库中存在相同记录！");
                                            } else {
                                                $("#create-and-edit-one-goods-form").find('div.create-goods-dialog-err').empty().css({
                                                    "color": "red",
                                                    "text-align": "center"
                                                }).text("操作失败，请按确认按钮再次提交！");
                                            }
                                        }
                                    }
                                });
                                dialog.show();
                                //加载文件DOM
                                $("#create-content").load("static/html/goods-dialog.html #create-and-edit-one-goods-form", function() {
                                    bui_form = new Form.Form({
                                        srcNode: '#create-and-edit-one-goods-form'
                                    }).render();
                                    //把值赋给form中元素，并设置不可用
                                    bui_form.setFieldValue("Warehouseid", wTreeNode.Name);
                                    bui_form.getField("Warehouseid").disable();
                                });
                            });
                        }
                    }

                }, {
                    btnCls: 'btn btn-primary btn-sm goods-edit-btn',
                    text: '修改',
                    listeners: {
                        'click': function() {
                            var list = grid.getSelection();
                            var openChooseWarehouseDialog = function(bui_form) {
                                var nowWarehouseId = "";
                                //获取form字段
                                var bui_warehouse = bui_form.getField("Warehouseid");
                                //为字段添加点击事件
                                bui_warehouse.on('click', function() {
                                    var nowClickNode = "";
                                    //ztree强行异步加载，并展开指定节点
                                    var ztreeRe = function() {
                                        var stree = $.fn.zTree.getZTreeObj("sideTree");
                                        stree.reAsyncChildNodes(null, "refresh");
                                        stree.setting.callback.onAsyncSuccess = function(event, treeId, treeNode, msg) {
                                            var node = stree.getNodeByParam("Id", wTreeNode.Id, null);
                                            stree.selectNode(node);
                                        };
                                    };
                                    BUI.use(['bui/overlay'], function(Overlay) {
                                        var dialog = new Overlay.Dialog({
                                            title: '选择仓库',
                                            width: 400,
                                            height: 300,
                                            zIndex: '1200',
                                            closeAction: 'destroy',
                                            bodyContent: "<div id=\"inputWarehouse\"></div>",
                                            success: function() {
                                                //如果不是父节点并且不是开始默认选中的节点
                                                if (nowClickNode != "") {
                                                    if (nowClickNode != wTreeNode.Name) {
                                                        //为表单字段设置值
                                                        bui_form.setFieldValue("Warehouseid", nowClickNode);
                                                        bui_form.set("warehouse_id", nowWarehouseId);
                                                        //关闭dialog
                                                        this.close();

                                                    } else {
                                                        bui_form.setFieldValue("Warehouseid", "");
                                                        this.close();
                                                        alert("选择的仓库没有变，请重新选择!");
                                                    }

                                                }
                                                ztreeRe();
                                            },
                                            cancel: function() {
                                                ztreeRe();
                                            }
                                        });
                                        dialog.show();
                                        //选择的tree
                                        warehouseTree("inputWarehouseTree", "#inputWarehouse");
                                        var wtree = $.fn.zTree.getZTreeObj("inputWarehouseTree");
                                        //ztree点击回调函数
                                        wtree.setting.callback.onClick = function(event, treeId, treeNode, clickFlag) {
                                            //如果当前节点没有子节点
                                            if (treeNode.isParent == false) {
                                                nowClickNode = treeNode.Name;
                                                nowWarehouseId = treeNode.Id;
                                            } else {
                                                nowClickNode = "";
                                            }
                                        };
                                        //ztree异步加载成功后回调函数
                                        wtree.setting.callback.onAsyncSuccess = function(event, treeId, treeNode, msg) {
                                            var node = wtree.getNodeByParam("Id", wTreeNode.Id, null);
                                            wtree.selectNode(node);
                                            nowClickNode = node.Name;
                                        };
                                        //ztree编辑名称结束之后的事件回调函数
                                        wtree.setting.callback.onRename = function(event, treeId, treeNode, isCancel) {
                                            nowClickNode = wtree.getSelectedNodes()[0].Name;
                                        }
                                    });
                                });
                            };
                            if (list.length == 1) { //修改一条记录
                                //var item = grid.getSelected();
                                BUI.use(['bui/overlay', 'bui/form'], function(Overlay, Form) {
                                    var bui_form;
                                    var dialog = new Overlay.Dialog({
                                        title: '修改物品',
                                        width: 500,
                                        height: 480,
                                        //关闭后删除dialog
                                        closeAction: 'destroy',
                                        bodyContent: "<div id=\"edit-one-content\"></div>",
                                        success: function() {
                                            if (bui_form.isValid()) { //form验证OK
                                                var obj = bui_form.serializeToObject();
                                                obj.Id = Number(list[0]._id);
                                                obj.Warehouseid = bui_form.get("warehouse_id");
                                                obj.Quantity = parseFloat(obj.Quantity);
                                                obj.Price = parseFloat(obj.Price);
                                                //alert(obj.Warehouseid);
                                                var data = postData(BUI.JSON.stringify(obj), "/green/goods/update");
                                                if (data.Status == 0) { //数据库操作OK
                                                    this.close();
                                                    store.load();
                                                    store.on("load", function() {
                                                        grid.setSelectedByField("_id", obj.Id);
                                                    });
                                                } else {
                                                    $("#create-and-edit-one-goods-form").find('div.edit-goods-dialog-err').empty().css({
                                                        "color": "red",
                                                        "text-align": "center"
                                                    }).text("操作失败，请按确认按钮再次提交！");
                                                }
                                            }
                                        }
                                    });
                                    dialog.show();
                                    $("#edit-one-content").load("static/html/goods-dialog.html #create-and-edit-one-goods-form", function() {
                                        //加载好后生成form
                                        bui_form = new Form.Form({
                                            srcNode: '#create-and-edit-one-goods-form'
                                        }).render();
                                        //弹出选择仓库对话框
                                        openChooseWarehouseDialog(bui_form);
                                        //设置form
                                        bui_form.set("warehouse_id", wTreeNode.Id);
                                        bui_form.set("record", {
                                            Number: list[0]._number,
                                            Name: list[0]._name,
                                            Specification: list[0]._specification,
                                            Warehouseid: wTreeNode.Name,
                                            Quantity: list[0]._quantity,
                                            QuantityUnit: list[0]._quantityunit,
                                            Price: list[0]._price,
                                            PriceUnit: list[0]._priceunit
                                        });
                                    });
                                });
                            } else { //修改多条记录
                                var idList = new Array();
                                $.each(list, function(index, val) {
                                    idList.push(val._id);
                                });

                                BUI.use(['bui/overlay', 'bui/form'], function(Overlay, Form) {
                                    var bui_form;
                                    var nowWarehouseId = "";
                                    //自定义验证规则
                                    new Form.Rules.add({
                                        name: 'editInput',
                                        msg: '请输入汉字/英文字母/数字/中杠“-”/下杠“_”',
                                        validator: function(value, baseValue, formatMsg) {
                                            var regexp = new RegExp(baseValue);
                                            if (value != "") {
                                                if (value && !regexp.test(value)) {
                                                    return formatMsg;
                                                } else {
                                                    if (value.length < 1) {
                                                        return "请输入长度大于6的字符"
                                                    } else if (value.length > 20) {
                                                        return "请输入长度小于20的字符"
                                                    }
                                                }
                                            }
                                        }
                                    });

                                    var dialog = new Overlay.Dialog({
                                        title: '批量修改物品',
                                        width: 500,
                                        height: 510,
                                        //关闭后删除dialog
                                        closeAction: 'destroy',
                                        bodyContent: "<div id=\"edit-multi-content\"></div>",
                                        success: function() {
                                            //form验证OK
                                            if (bui_form.isValid()) {
                                                var obj = bui_form.serializeToObject();
                                                var newData = {
                                                    "_modify_id_list": idList
                                                };

                                                if (obj.Name != "") {
                                                    newData._name = obj.Name;
                                                }

                                                if (obj.Specification != "") {
                                                    newData._specification = obj.Specification;
                                                }

                                                if (obj.Warehouseid != "") {
                                                    // newData._warehouseid = nowWarehouseId;
                                                    newData._warehouseid = bui_form.get("warehouse_id");
                                                }

                                                if (obj.Quantity != "") {
                                                    newData._quantity = parseFloat(obj.Quantity);
                                                }

                                                if (obj.QuantityUnit != "") {
                                                    newData._quantityunit = obj.QuantityUnit;
                                                }

                                                if (obj.Price != "") {
                                                    newData._price = parseFloat(obj.Price);
                                                }

                                                if (obj.PriceUnit != "") {
                                                    newData._priceunit = obj.PriceUnit;
                                                }

                                                //var s = bui_form.get("warehouse_id");
                                                //console.log(s);

                                                var data = postData(BUI.JSON.stringify(newData), "/green/goods/multiupdate");
                                                if (data.Status == 0) { //数据库操作OK
                                                    this.close();
                                                    store.load();
                                                    store.on("load", function() {
                                                        //console.log("共计：" + store.getCount());
                                                        grid.setSelectionByField("_id", idList);
                                                    });
                                                } else {
                                                    $("#create-and-edit-one-goods-form").find('div.edit-goods-dialog-err').empty().css({
                                                        "color": "red",
                                                        "text-align": "center"
                                                    }).text("操作失败，请按确认按钮再次提交！");
                                                }
                                            }
                                        }
                                    });
                                    dialog.show();
                                    $("#edit-multi-content").load("static/html/goods-dialog.html #edit-multi-goods-form", function() {
                                        bui_form = new Form.Form({
                                            autoRender: true,
                                            srcNode: '#edit-multi-goods-form'
                                        });
                                        //弹出选择仓库对话框
                                        openChooseWarehouseDialog(bui_form);
                                    });
                                });
                            }
                        }
                    }
                }, {
                    btnCls: 'btn btn-primary btn-sm goods-delete-btn',
                    text: '删除',
                    listeners: {
                        'click': function() {
                            var list = grid.getSelection();
                            if (list.length == 1) { //删除一条记录
                                BUI.use(['bui/overlay'], function(Overlay) {
                                    BUI.Message.Confirm('确认要删除么？', function() {
                                        var data = getData("/green/goods/delete/" + list[0]._id);
                                        if (data.Status == 0) { //数据库操作OK
                                            store.load();
                                        }
                                    }, 'question');
                                });
                            } else { //删除多条记录
                                var idList = new Array();
                                $.each(list, function(index, val) {
                                    idList.push(val._id);
                                });
                                BUI.use(['bui/overlay'], function(Overlay) {
                                    BUI.Message.Confirm('确认要删除么？', function() {
                                        var data = postData(BUI.JSON.stringify(idList), "/green/goods/multidelete");
                                        if (data.Status == 0) { //数据库操作OK
                                            store.load();
                                        } else {
                                            setTimeout(function() {
                                                BUI.Message.Show({
                                                    msg: '删除失败，请重试！',
                                                    icon: 'error',
                                                    buttons: [],
                                                    autoHide: true,
                                                    autoHideDelay: 2000
                                                });
                                            });
                                        }
                                    }, 'question');
                                });
                            }
                        }
                    }
                }]
            },
            bbar: {
                //分页栏
                pagingBar: {
                    //store: store,
                    totalPageTpl: "共" + totalPage + "页",
                    totalCountTpl: "共" + totalCount + "条记录"
                }
            }
        });

        //数字分页
        // var bar = new Toolbar.NumberPagingBar({
        //     render: '#my-table-nav',
        //     elCls: 'pagination pull-right',
        //     store: store
        // });
        // bar.render();

        grid.render();
        var tbar = grid.get('tbar');
        //搜索工具栏
        // var searchBar = new Toolbar.Bar({
        //     elCls: 'pull-right',
        //     items: [{
        //         content: '<input type="text" id="table-search" class="table-search "/>'
        //     }, {
        //         xclass: 'bar-item-button',
        //         btnCls: 'btn btn-primary table-search-btn btn-sm',
        //         text: '搜索'
        //     }]
        // });
        // tbar.addChild(searchBar);
        //默认删改按钮不可用
        tbar.getItemAt(0).getItemAt(1).disable();
        tbar.getItemAt(0).getItemAt(2).disable();
        //选择增删改按钮是否可用
        grid.on('selectedchange', function(e) {
            var list = grid.getSelection();
            if (list.length > 0) {
                tbar.getItemAt(0).getItemAt(0).disable();
                tbar.getItemAt(0).getItemAt(1).enable();
                tbar.getItemAt(0).getItemAt(2).enable();
            } else {
                tbar.getItemAt(0).getItemAt(0).enable();
                tbar.getItemAt(0).getItemAt(1).disable();
                tbar.getItemAt(0).getItemAt(2).disable();
            }
        });

        //var pbar = grid.get('bbar').get("pagingBar");
        var pbar = grid.get("bbar").getChildAt(0);
        //pbar.totalPageTpl = "共500页";
        //pbar.set("totalPageTpl", "共500页");
        var first = pbar.getChildAt(0);
        //first.get("firs");
        alert(first.id);
    });
}

//基本的warehouse tree显示
function warehouseTree(treeId, appendToDomId) {
    var rMenu = null,
        oldTreeNodeName = "",
        $rMenu = null,
        addCount = 1;

    //自动隐藏的消息提示框
    var buiMessage = function(str) {
        BUI.use(['bui/overlay'], function(Overlay) {
            BUI.Message.Show({
                msg: str,
                icon: 'warning',
                buttons: [],
                autoHide: true,
                autoHideDelay: 1000
            });
        });
    };

    //鼠标点击事件
    var onBodyMouseDown = function(event) {
        if (!(event.target.id == "tree-rMenu" || $(event.target).parents("#tree-rMenu").length > 0)) {
            removeRMenu();
        }
    };

    //创建右键菜单
    var createRMenu = function(type, x, y) {
        $("#tree-rMenu").remove();
        $rMenu = $("<ul id=\"tree-rMenu\" class=\"dropdown-menu tree-rMenu\"><li id=\"m_add\"><a href=\"#\">增加</a></li><li id=\"m_rename\"><a href=\"#\">重命名</a></li><li id=\"m_del\"><a href=\"#\">删除</a></li></ul>");
        if (type == "root") {
            $rMenu.find("#m_del").remove();
            $rMenu.find("#m_rename").remove();
        }
        $rMenu.css({
            "top": y + "px",
            "left": x + "px",
            "z-index": 2000
        }).addClass("show").appendTo("body");

        //ztree添加一个新节点
        $(document).on("click", "#m_add", function() {
            addTreeNode();
        });

        //ztree修改一个节点名称
        $(document).on("click", "#m_rename", function() {
            var nNode = $.fn.zTree.getZTreeObj(treeId).getSelectedNodes()[0];
            nNode.Ev = 1; //表示更新分类
            editTreeNode(nNode);
        });

        //ztree删除一个节点
        $(document).on("click", "#m_del", function() {
            var stree = $.fn.zTree.getZTreeObj(treeId);
            var nNodes = stree.getSelectedNodes();
            var fNode = nNodes[0].getParentNode();
            if (nNodes && nNodes.length > 0) {
                var isParent = nNodes[0].isParent;
                //alert(isParent);
                if (isParent == false) { //不是父节点，直接删除
                    //隐藏右键菜单 -> 增加删除对话框 -> 点击确认按钮删除
                    removeRMenu();
                    var goods = {
                        "Warehouseid": nNodes[0].Id
                    };
                    var data = postData(BUI.JSON.stringify(goods), "/green/goods/count");
                    if (data.ServerError == false) { //数据库操作OK
                        if (data.Data > 0) { //该分类下有物品
                            var nowClickNode = "";
                            //ztree强行异步加载，并展开指定节点
                            var ztreeRe = function() {
                                stree.reAsyncChildNodes(null, "refresh");
                                stree.setting.callback.onAsyncSuccess = function(event, treeId, treeNode, msg) {
                                    var node = stree.getNodeByParam("Id", fNode.Id, null);
                                    stree.expandNode(node, true, false, true);
                                };
                            };
                            BUI.use(['bui/overlay'], function(Overlay) {
                                var dialog = new Overlay.Dialog({
                                    title: '选择仓库',
                                    width: 400,
                                    height: 300,
                                    zIndex: '1200',
                                    closeAction: 'destroy',
                                    bodyContent: "<div id=\"inputWarehouse\"><p></p></div>",
                                    success: function() {
                                        //如果不是父节点并且不是开始默认选中的节点
                                        if (nowClickNode != "") {
                                            if (nowClickNode != nNodes[0].Name) {
                                                var data = postData(BUI.JSON.stringify(goods), "/green/goods/updatemulti");
                                                //关闭dialog
                                                this.close();
                                                //alert(nowClickNode);
                                            } else {
                                                this.close();
                                                buiMessage("选择的仓库没有变，请重新选择!");
                                            }

                                        } else {
                                            buiMessage("只可以移动到子分类，请重新选择!");
                                        }
                                        ztreeRe();
                                    },
                                    cancel: function() {
                                        ztreeRe();
                                    }
                                });
                                dialog.show();
                                $("#inputWarehouse p").text("删除的分类下有物品，请先把物品转移到其他分类下面!");
                                //选择的tree
                                warehouseTree("inputWarehouseTree", "#inputWarehouse");
                                var wtree = $.fn.zTree.getZTreeObj("inputWarehouseTree");
                                //ztree点击回调函数
                                wtree.setting.callback.onClick = function(event, treeId, treeNode, clickFlag) {
                                    //如果当前节点没有子节点
                                    if (treeNode.isParent == false) {
                                        nowClickNode = treeNode.Name;
                                    } else {
                                        nowClickNode = "";
                                    }
                                };
                                //ztree异步加载成功后回调函数
                                wtree.setting.callback.onAsyncSuccess = function(event, treeId, treeNode, msg) {
                                    var node = wtree.getNodeByParam("Id", nNodes[0].Id, null);
                                    wtree.expandNode(node.getParentNode(), true, false, true);
                                    wtree.removeNode(node);
                                };
                                //ztree编辑名称结束之后的事件回调函数
                                wtree.setting.callback.onRename = function(event, treeId, treeNode, isCancel) {
                                    nowClickNode = wtree.getSelectedNodes()[0].Name;
                                };

                            });
                        } else { //该分类下没有物品
                            alert("直接删除数据！");
                        }
                    } else { //操作数据库错误
                        removeRMenu();
                        alert("数据库操作出错！");
                    }
                }
            }
        });
        $("body").on("mousedown", onBodyMouseDown);
    };

    //删除右键菜单
    var removeRMenu = function() {
        if ($rMenu) {
            $rMenu.remove();
        }
        $(document).off("click", "#m_add");
        $(document).off("click", "#m_rename");
        $(document).off("click", "#m_del");
        $("body").off("mousedown", onBodyMouseDown);
    };

    //修改节点名称
    var editTreeNode = function(nNode) {
        removeRMenu();
        if (nNode) {
            oldTreeNodeName = nNode.Name;
            $.fn.zTree.getZTreeObj(treeId).editName(nNode);
        }
    };

    //获取节点，并且编辑这个节点
    var getAndEditNode = function(zTree, fNode) {
        var nNode = zTree.getNodeByParam("temp", addCount, null);
        nNode.temp = 0; //先把addCount临时保存到temp中，然后通过addCount找到这个节点，再把temp归零
        nNode.Ev = 0; //表示新增分类
        if (fNode) {
            nNode.Fid = fNode.Id;
        } else {
            nNode.Fid = "0";
        }
        editTreeNode(nNode);
        addCount++;
    };

    //添加树节点
    var addTreeNode = function() {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        removeRMenu();
        var newNode = {
            Name: "新增" + addCount,
            temp: addCount
        };
        oldTreeNodeName = newNode.Name;
        var fNode = zTree.getSelectedNodes()[0];
        if (fNode) {
            zTree.addNodes(fNode, newNode);
            getAndEditNode(zTree, fNode);
        } else {
            zTree.addNodes(null, newNode);
            getAndEditNode(zTree, fNode);
        }
    };


    //删除节点
    var removeTreeNode = function(nNodes) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        //beforeRemove("#tree", nNode);
        // alert(nNodes[0].children);
        // if (nNodes[0].children && nNodes[0].children.length > 0) {
        //  var msg = "要删除的节点是父节点，如果删除将连同子节点一起删掉。\n\n请确认！";
        //  if (confirm(msg) == true) {
        //      zTree.removeNode(nNodes[0]);
        //  }
        // } else {
        //  zTree.removeNode(nNodes[0]);
        // }

        if (nNodes[0].children && nNodes[0].children.length > 0) { //有子节点
            nNodes[0].Re = 1;
            //alert("f   ID："+nNodes[0].Id);
            //beforeRemove("tree", nNodes[0]);

            zTree.removeNode(nNodes[0]);
        } else { //没有子节点
            nNodes[0].Re = 0;
            //alert("z   ID："+nNodes[0].Id);
            //beforeRemove("tree", nNodes[0]);

            zTree.removeNode(nNodes[0]);
        }

    };

    //弹出一个简单的对话框
    var simpleDialog = function(contentStr) {
        $("body").append($("<div id=\"ztree-simple-dialog\"></div>"));
        $("#ztree-simple-dialog").dialog({
            content: contentStr,
            showBtn: false
        });
        setTimeout(function() {
            $("#ztree-simple-dialog").dialog("close");
        }, 3000);
    };

    //ztree onRightClick回调函数
    var onRightClick = function(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
            zTree.cancelSelectedNode();
            createRMenu("root", event.pageX, event.pageY);
        } else if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            createRMenu("node", event.pageX, event.pageY);
        }
    };

    //ztree beforeRename回调函数
    var beforeRename = function(treeId, treeNode, newName, isCancel) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        if (newName.length == 0) {
            buiMessage("内容不能为空!");
            zTree.editName(treeNode);
            return false;
        } else {
            treeNode.Name = newName;
            if (treeNode.Ev == 0) { //如果Ev=0，创建新分类
                if (isCancel == true) { //按ESC键删除刚创建的treeNode
                    zTree.removeNode(treeNode);
                } else {
                    var data = postData(JSON.stringify(treeNode), "/green/warehouse/create");
                    if (data.Status == 1) { //数据库操作出错
                        buiMessage("数据库操作出错，请重试！");
                        zTree.cancelEditName(oldTreeNodeName);
                    } else if (data.Status == 2) {
                        buiMessage("分类下有物品，不可创建子分类！");
                        zTree.cancelEditName(oldTreeNodeName);
                    } else if (data.Status == 3) {
                        buiMessage("名称重复，请修改!");
                        zTree.editName(treeNode);
                        return false;
                    } else {
                        treeNode.Id = data.Data;
                        zTree.updateNode(treeNode);
                    }
                }

            } else { //如果Ev!=0，更新分类
                if (treeNode.Name != oldTreeNodeName) {
                    var data = postData(JSON.stringify(treeNode), "/green/warehouse/update");
                    if (data.Status == 1) { //数据库就操作出错
                        buiMessage("数据库操作出错，请重试！");
                        zTree.cancelEditName(oldTreeNodeName);
                    } else if (data.Status == 2) {
                        buiMessage("名称重复，请修改!");
                        treeNode.Name = oldTreeNodeName;
                        zTree.editName(treeNode);
                        return false;
                    } else {
                        zTree.updateNode(treeNode); //更新Node
                    }
                }
            }
        }
        return true;
    };

    //ztree beforeRemove回调函数
    // function beforeRemove(treeId, treeNode) {
    //  //alert("ID：" + treeNode.Id);
    //  //return false;
    // }

    //ztree onRemove回调函数
    // function onRemove(event, treeId, treeNode) {
    //  alert("删除ID: " + treeNode.Id);
    //  $("#ztree-del-dialog").dialog("close");
    // }

    $("<ul id=\"" + treeId + "\" class=\"ztree\"></ul>").appendTo(appendToDomId);
    //初始化ztree
    var setting = {
        edit: {
            enable: true,
            showRemoveBtn: false,
            showRenameBtn: false,
            drag: {
                isCopy: false,
                isMove: false
            }
        },
        async: {
            enable: true,
            url: "/green/warehouse/list"
        },
        data: {
            key: {
                name: "Name"
            },
            simpleData: {
                enable: true,
                idKey: "Id",
                pIdKey: "Fid",
                rootPId: 0
            }
        },
        callback: {
            beforeRename: beforeRename,
            //beforeRemove: beforeRemove,
            //onRename: onRename,
            //onRemove: onRemove,
            //onAsyncSuccess: onAsyncSuccess,
            //onClick: onClick,
            onRightClick: onRightClick
        }
    };
    $.fn.zTree.init($("#" + treeId), setting);
}